const mongoose = require("mongoose");
module.exports = app => {
    const express = require("express")
    const router = express.Router({
        mergeParams: true   //导入父级参数到子级配置
    });
    //快速验证,抛出异常
    const assert = require('http-assert');
    //中间件- 验证用户token返回id
    const auth = require(`../../middle/auth`)(app, ["admin", "user"])
    // APP的数据库
    const APP = require(`../../models/noteMode`);

    router.post('/', async (req, res) => {
        req.body.logs = [{
            user: req.user.id,
            date: new Date()
        }]
        // req.body.user = req.user.id;
        const car = await APP.create(req.body);
        assert(car, 401, "新建保存失败");
        res.send(car)
    })

    router.put('/', async (req, res) => {
        req.body.logs.push({
            user: req.user.id,
            date: new Date()
        })
        const APP = req.body;
        // delete APP.fID;
        const APPp = await APP.findByIdAndUpdate(req.body._id, APP);
        res.send(APPp)
    })

    router.get('/:id', async (req, res) => {
        const APP = await APP.findById(req.params.id)
        res.send(APP)
    })

    router.delete('/', async (req, res) => {
        // await APP.findByIdAndDelete(req.params.id);
        await APP.deleteMany()
        // mongoose.model.remove("APP")
        res.send({ msg: 200 })
    })

    //post获取列表
    router.get('/', async (req, res) => {
        let data = {
            total: 10,
            current: 1,
            size: 10,
            search: "",
        }
        if (req.query.search) {
            data = JSON.parse(req.query.search);
        }


        let _filter = {
            $or: [  // 多字段同时匹配
                { "name": { $regex: data.search || '' } },
                // { "APPID": { $regex: data.search || '' } }, //  $options: '$i' 忽略大小写
            ]
        }
        // console.log(_filter.$or)
        const { size = 10, current = 1 } = data;
        let total = await APP.countDocuments()
        let list = [];
        // .populate(["APPegory", "user"])
        list = await APP.find(_filter).populate([{ path: 'logs.user', select: "name" }]).skip(size * (current - 1)).limit(size).sort({ _id: -1 });
        console.log('list', list[0])
        const page = {
            total,
            size,
            current,
            list
        };
        // console.log('list', list)
        res.send(page)
    })
    app.use('/admin/api/noteMode', auth, router);
    //错误函数处理
    app.use(async (err, req, res, next) => {
        console.log(err)
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}